package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.pojo.EmpQueryParam;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    /*@Override
    public PageBean page1(Integer page, Integer pageSize) {
        //1.调用mapper接口获取总记录数 total
        Long total = empMapper.count();

        //2.调用mapper接口 获取结果列表 rows
        //计算起始索引
        Integer start = (page - 1) * pageSize;
        List<Emp> rows = empMapper.list(start , pageSize);
        *//* 3.封装结果 *//*
        return new PageBean(total,rows);
    }*/

    @Override
    public PageBean page(EmpQueryParam queryParam) {
        //1. 设置分页参数
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());

        //2. 执行查询
        List<Emp> empList = empMapper.list(queryParam);

        //3. 解析封装分页结果
        Page<Emp> p = (Page<Emp>) empList;

        return new PageBean(p.getTotal(), p.getResult());
    }
    @Transactional(rollbackFor = {Exception.class})//事务管理的注解
    @Override
    public void add(Emp emp) {
        //1.调用empMapper保存员工的基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

       // int i =1/0;

        empMapper.insert(emp);
        //2.调用empExprMapper
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> {
                empExpr.setEmpId(emp.getId());
            });
        }
        empExprMapper.insertBatch(exprList);
    }


}
